/*小程序码扫码方式登录*/

import {onMounted, ref} from "vue";
import {Message} from "view-ui-plus";
import {getUserInfoBySceneCodeApi, getWXACodeUnlimited as getWXACodeUnlimitedApi} from "@/module-base/api/login.js";
import {useLoginStore} from "@/module-base/stores/login.js";
import {useRouter} from 'vue-router'

export function useLoginMiniApp() {
    const {handleLogIn: handleLogIn} = useLoginStore()
    const router = useRouter()

    onMounted(async ()=>{
        // miniAppQrcodeUrl.value = (await import('@/assets/images/miniApp.jpg')).default
        await loginBySceneCode()
    })

    /**
     * 小程序码方式登录逻辑*/
    const loadingImg = ref(false)
    const showRefreshCode = ref(false)

    /**
     * 获取小程序码，轮询是否扫码登录*/
    async function loginBySceneCode() {
        // 开发模式下，直接进入首页
        // toHomePage()
        // return
        showRefreshCode.value = false
        loadingImg.value = true
        const sceneCode = await getWXACodeUnlimited()
        loadingImg.value = false
        getUserInfoBySceneCode(sceneCode)
    }

    let getUserInfoInterval = ref(null)

    /**
     *根据小程序码参数轮询用户信息 */
    function getUserInfoBySceneCode(sceneCode) {
        if (!sceneCode) return
        let getApiCount = 0 //当前轮询次数
        let maxApiCount = 3  //最大的轮询次数
        let getApiSuccess = false //轮询是否成功

        getUserInfoInterval.value = setInterval(async () => {
            if (getApiCount >= maxApiCount) {
                // 超过10次，停止轮询
                clearInterval(getUserInfoInterval.value);
                showRefreshCode.value = true
                if (getApiCount === maxApiCount && !getApiSuccess) {
                    // 十次轮询都未成功，显示错误信息
                    console.error('十次轮询均失败:', getApiSuccess);
                    Message.error('扫码登录失败，请重试');
                    showRefreshCode.value = true;
                }
            }
            getApiCount++
            try {
                const userInfoRs = await getUserInfoBySceneCodeApi({
                    sceneCode: sceneCode
                })
                if (userInfoRs.success) {
                    getApiSuccess = true
                    Message.success('扫码登录成功')
                    // 登录成功后，维护全局变量
                    await handleLogIn(userInfoRs)
                    router.push({name: 'home'})
                    // 成功后停止轮询
                    clearInterval(getUserInfoInterval.value);
                }
            } catch (error) {
                console.error('根据小程序码参数获取用户信息失败:', error);
            }
        }, 3000); // 每3秒轮询一次
    }

    /**
     * 获取小程序码
     * 返回值-小程序码参数*/
    const miniAppSceneCodeUrl = ref('') //带参数的二维码
    async function getWXACodeUnlimited() {
        miniAppSceneCodeUrl.value = ''
        let imgRs = {}
        try {
            imgRs = await getWXACodeUnlimitedApi({
                env_version: 'release',
            });
        } catch (e) {
            imgRs = {
                success: false
            }
        }
        // 将 Buffer 数据转换为图片 URL
        // 1. 将数组转换为 Uint8Array
        const uint8Array = new Uint8Array(imgRs.data.imgData.data);

        // 2. 将 Uint8Array 转换为 Blob
        const blob = new Blob([uint8Array], {type: 'image/png'}); // 根据实际图片类型设置 MIME 类型

        // 3. 生成图片 URL
        miniAppSceneCodeUrl.value = URL.createObjectURL(blob);
        return imgRs.data.cId
    }

    return {
        loadingImg,
        showRefreshCode,
        loginBySceneCode,
        getUserInfoBySceneCode,
        // miniAppQrcodeUrl,
        miniAppSceneCodeUrl,
        getWXACodeUnlimited,
        getUserInfoInterval
    }
}